/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-06-19
 * Time: 23:26
 */
//力扣：https://leetcode.cn/problems/remove-linked-list-elements/description/
// 给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点 。
class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    public static void printNode(ListNode list){
        System.out.print("[");
        while(list!=null){
            System.out.print(" "+list.val);
            list=list.next;
        }
        System.out.print(" ]");
    }
 }
public class Test {
    public static ListNode removeElements(ListNode head, int val) {
        if(head==null){
            return head;
        }
        ListNode p2=head;
        ListNode p1=head.next;
        while(p1!=null){
            if(p1.val==val){
                p2.next=p1.next;
                p1=p1.next;
            }
            else{
                p2=p1;
                p1=p1.next;
            }
        }
        if(head.val==val){
            head=head.next;
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode list5 = new ListNode(3,null);
        ListNode list4 = new ListNode(5,list5);
        ListNode list3 = new ListNode(2,list4);
        ListNode list2 = new ListNode(5,list3);
        ListNode list1 = new ListNode(1,list2);
        ListNode head=removeElements(list1,5);
        ListNode.printNode(head);
    }
}
